package com.ruoyi.web.core.config.mqtt;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.config.SystemConfig;
import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.service.ICommonService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author chmj
 * @version V1.0
 * @Package com.radar.util.mqtt
 * @Copyright 2022/9/13 16:37 汇博医疗股份有限公司
 */
@Slf4j
public class MqttFactory {

    private static MqttClient client;

    /**
     *   获取客户端实例
     *   单例模式, 存在则返回, 不存在则初始化
     */
    public static MqttClient getInstance() {
        if (client == null) {
            init();
        }
        return client;
    }

    /**
     *   初始化客户端
     */
    public static void init() {
        MqttProperties configuration = SpringUtils.getBean(MqttProperties.class);
        try {
            client = new MqttClient(configuration.getAddress(), configuration.getClientId());
            // MQTT配置对象
            MqttConnectOptions options = new MqttConnectOptions();
            // 设置自动重连, 其它具体参数可以查看MqttConnectOptions
            options.setUserName(configuration.getUsername());
            options.setPassword(configuration.getPassword().toCharArray());
            options.setCleanSession(false);
            options.setConnectionTimeout(3000);
            options.setKeepAliveInterval(60);
            // 设置自动重连, 其它具体参数可以查看MqttConnectOptions
            options.setAutomaticReconnect(true);
            if (!client.isConnected()) {
                client.connect(options);
            }else{
                client.disconnect();
                client.connect(options);
            }
            client.setCallback(new MqttReconnectCallback());
        } catch (MqttException e) {
            log.error("MQTT: 连接消息服务器{}失败", configuration.getAddress());
        }
    }
}
